package com.catazy.wanandroid.common_base.glide

import okhttp3.Interceptor
import okhttp3.Response

/**
 * 作者: Tao
 * 日期: 2024/4/10
 * 时间: 11:38
 * 描述: 进度拦截器
 *  这里class用object感觉有点问题样子，后面再来看怎么调整下
 */
object ProgressInterceptor : Interceptor {

    private val LISTENER_MAP = hashMapOf<String, ProgressListener>()

    /**
     * 获取监听
     */
    fun getListener(url: String): ProgressListener? {
        return LISTENER_MAP[url]
    }

    /**
     * 添加监听
     */
    fun addListener(url: String, listener: ProgressListener) {
        if (LISTENER_MAP.containsKey(url)) {
            return
        }
        LISTENER_MAP[url] = listener
    }

    /**
     * 移除监听
     */
    fun removeListener(url: String) {
        LISTENER_MAP.remove(url)
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val url = request.url.toString()
        val responseBody = response.body
        return response.newBuilder().body(ProgressResponseBody(url, responseBody!!)).build()
    }
}